package com.example.common.interceptor;


import cn.hutool.core.util.StrUtil;
import com.example.common.utils.RoleContext;
import com.example.common.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;


@Slf4j
public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("公共拦截器拦截到请求");
        // 1.获取请求头中的用户
        String userInfo = request.getHeader("user-info");
        String roleInfo = request.getHeader("role-info");
        // 2.判断是否为空，不为空，存入UserContext
        if (StrUtil.isNotBlank(userInfo)) {
            log.info("用户拦截器拦截到用户,存储到当前线程中: {}", userInfo);
            UserContext.setUser(userInfo);
            RoleContext.setRole(String.valueOf(roleInfo));
        }
        System.out.println("放行！");
        // 3.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除用户
        UserContext.removeUser();
        RoleContext.removeRole();
    }
}
